import {validatenull} from './validate'
import request from '@/router/axios';
export const detailData = (data, list) => {
  list.forEach(ele => {
    if (data[ele]) {
      data[`${ele}_eq`] = data[ele]
      delete data[ele]
    }
  })
  return data
}
//表单序列化
export const serialize = data => {
  var formdata = new FormData()
  Object.keys(data).forEach(ele => {
    if (data[ele] != null){
      formdata.append(ele, data[ele]);
    }
  })
  return formdata
};
export const getObjType = obj => {
  var toString = Object.prototype.toString;
  var map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object'
  };
  if (obj instanceof Element) {
    return 'element';
  }
  return map[toString.call(obj)];
};
export const getViewDom = () => {
  return window.document.getElementById('avue-view').getElementsByClassName('el-scrollbar__wrap')[0]
}
/**
 * 对象深拷贝
 */
export const deepClone = data => {
  var type = getObjType(data);
  var obj;
  if (type === 'array') {
    obj = [];
  } else if (type === 'object') {
    obj = {};
  } else {
    //不再具有下一层次
    return data;
  }
  if (type === 'array') {
    for (var i = 0, len = data.length; i < len; i++) {
      obj.push(deepClone(data[i]));
    }
  } else if (type === 'object') {
    for (var key in data) {
      obj[key] = deepClone(data[key]);
    }
  }
  return obj;
};
/**
 * 设置灰度模式
 */
export const toggleGrayMode = (status) => {
  if (status) {
    document.body.className = document.body.className + ' grayMode';
  } else {
    document.body.className = document.body.className.replace(' grayMode', '');
  }
};
/**
 * 设置主题
 */
export const setTheme = (name) => {
  document.body.className = name;
}

/**
 * 加密处理
 */
export const encryption = (params) => {
  let {
    data,
    type,
    param,
    key
  } = params;
  let result = JSON.parse(JSON.stringify(data));
  if (type == 'Base64') {
    param.forEach(ele => {
      result[ele] = btoa(result[ele]);
    })
  } else if (type == 'Aes') {
    param.forEach(ele => {
      result[ele] = window.CryptoJS.AES.encrypt(result[ele], key).toString();
    })

  }
  return result;
};


/**
 * 浏览器判断是否全屏
 */
export const fullscreenToggel = () => {
  if (fullscreenEnable()) {
    exitFullScreen();
  } else {
    reqFullScreen();
  }
};
/**
 * esc监听全屏
 */
export const listenfullscreen = (callback) => {
  function listen () {
    callback()
  }
  document.addEventListener("fullscreenchange", function () {
    listen();
  });
  document.addEventListener("mozfullscreenchange", function () {
    listen();
  });
  document.addEventListener("webkitfullscreenchange", function () {
    listen();
  });
  document.addEventListener("msfullscreenchange", function () {
    listen();
  });
};
/**
 * 浏览器判断是否全屏
 */
export const fullscreenEnable = () => {
  var isFullscreen = document.isFullScreen || document.mozIsFullScreen || document.webkitIsFullScreen
  return isFullscreen;
}

/**
 * 浏览器全屏
 */
export const reqFullScreen = () => {
  if (document.documentElement.requestFullScreen) {
    document.documentElement.requestFullScreen();
  } else if (document.documentElement.webkitRequestFullScreen) {
    document.documentElement.webkitRequestFullScreen();
  } else if (document.documentElement.mozRequestFullScreen) {
    document.documentElement.mozRequestFullScreen();
  }
};
/**
 * 浏览器退出全屏
 */
export const exitFullScreen = () => {
  if (document.documentElement.requestFullScreen) {
    document.exitFullScreen();
  } else if (document.documentElement.webkitRequestFullScreen) {
    document.webkitCancelFullScreen();
  } else if (document.documentElement.mozRequestFullScreen) {
    document.mozCancelFullScreen();
  }
};
/**
 * 递归寻找子类的父类
 */

export const findParent = (menu, id) => {
  for (let i = 0; i < menu.length; i++) {
    if (menu[i].children.length != 0) {
      for (let j = 0; j < menu[i].children.length; j++) {
        if (menu[i].children[j].id == id) {
          return menu[i];
        } else {
          if (menu[i].children[j].children.length != 0) {
            return findParent(menu[i].children[j].children, id);
          }
        }
      }
    }
  }
};
/**
 * 判断2个对象属性和值是否相等
 */

/**
 * 动态插入css
 */

export const loadStyle = url => {
  const link = document.createElement('link');
  link.type = 'text/css';
  link.rel = 'stylesheet';
  link.href = url;
  const head = document.getElementsByTagName('head')[0];
  head.appendChild(link);
};
export const loadScript = url => {
  let flag = false;
  return new Promise((resolve) => {
    const head = document.getElementsByTagName('head')[0];
    head.children.forEach(ele => {
      if ((ele.src || '').indexOf(url) !== -1) {
        flag = true;
        resolve();
      }
    });
    if (flag) return
    const script = document.createElement('script');
    script.src = url;
    head.appendChild(script);
    script.onload = function () {
      resolve();
    };
  })
};
/**
 * 判断路由是否相等
 */
export const diff = (obj1, obj2) => {
  delete obj1.close;
  var o1 = obj1 instanceof Object;
  var o2 = obj2 instanceof Object;
  if (!o1 || !o2) { /*  判断不是对象  */
    return obj1 === obj2;
  }

  if (Object.keys(obj1).length !== Object.keys(obj2).length) {
    return false;
    //Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组,例如：数组返回下表：let arr = ["a", "b", "c"];console.log(Object.keys(arr))->0,1,2;
  }

  for (var attr in obj1) {
    var t1 = obj1[attr] instanceof Object;
    var t2 = obj2[attr] instanceof Object;
    if (t1 && t2) {
      return diff(obj1[attr], obj2[attr]);
    } else if (obj1[attr] !== obj2[attr]) {
      return false;
    }
  }
  return true;
}
/**
 * 把JSON转换成URL参数
 */
export const jsonToParams = (json) => {

  for(const key in json){
    if(validatenull(json[key])){
      delete json[key]
    }else if(key.startsWith("$")){
      delete json[key]
    }
  }
  return Object.keys(json).map(function (key) {
    if (!validatenull(json[key])) {
      return encodeURIComponent(key) + "=" + encodeURIComponent(json[key]);
    }
  }).join("&");
};
/**
 * 根据字典的value显示label
 */
export const findByvalue = (dic, value) => {
  let result = '';
  if (validatenull(dic)) return value;
  if (typeof (value) == 'string' || typeof (value) == 'number' || typeof (value) == 'boolean') {
    let index = 0;
    index = findArray(dic, value);
    if (index != -1) {
      result = dic[index].label;
    } else {
      result = value;
    }
  } else if (value instanceof Array) {
    result = [];
    let index = 0;
    value.forEach(ele => {
      index = findArray(dic, ele);
      if (index != -1) {
        result.push(dic[index].label);
      } else {
        result.push(value);
      }
    });
    result = result.toString();
  }
  return result;
};
/**
 * 根据字典的value查找对应的index
 */
export const findArray = (dic, value) => {
  for (let i = 0; i < dic.length; i++) {
    if (dic[i].value == value) {
      return i;
    }
  }
  return -1;
};
/**
 * 生成随机len位数字
 */
export const randomLenNum = (len, date) => {
  let random = '';
  random = Math.ceil(Math.random() * 100000000000000).toString().substr(0, len ? len : 4);
  if (date) random = random + Date.now();
  return random;
};
/**
 * 打开小窗口
 */
export const openWindow = (url, title, w, h) => {
  // Fixes dual-screen position                            Most browsers       Firefox
  const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left
  const dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top

  const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width
  const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height

  const left = ((width / 2) - (w / 2)) + dualScreenLeft
  const top = ((height / 2) - (h / 2)) + dualScreenTop
  const newWindow = window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left)

  // Puts focus on the newWindow
  if (window.focus) {
    newWindow.focus()
  }
};

/**
 * 生成Authorization
 * @param code
 * @param secret
 * @returns {string}
 */
export const getAuthorization = (code, secret) => {
  return "Basic "+btoa(code+":"+secret);
};


/**
 * 树形JSON加禁用属性
 * @returns {string}
 * @param tree
 * @param id
 */
export const treeAddDisabled = (tree, ids) => {
  tree.forEach(data => {

    if (data.children) {
      treeAddDisabled(data.children, ids);
    }


    let is = 'object' === typeof ids ? ids.includes(data.id) : data.id === ids;
    if (is) {
      data.disabled = true;

      //下级所有的子孙节点都不可选择
      if (data.children) {
        treeAddObj(data.children, {'disabled':true})
      }

    }else{
      data.disabled = false;
    }
  });

  return tree;
}

/**
 * 树形JSON加一个属性
 * @returns {string}
 * @param json 树形JSON
 * @param obj 添加的对象
 * @param callback 是否满足添加条件函数
 */
export const treeAddObj = (json, obj, callback = ()=>{return true}) => {

  json.forEach(data => {

    if (callback(data)){
      Object.assign(data, obj);
    }

    if (data.children) {
      treeAddObj(data.children,obj, callback);
    }

  });
}

/**
 * 树形JSON加一个属性
 * @returns {string}
 * @param json 树形JSON
 * @param callback 操作
 */
export const treeEditObj = (json, callback = ()=>{}) => {

  json.forEach(data => {

    callback(data);

    if (data.children) {
      treeEditObj(data.children, callback);
    }

  });
}

/**
 * 在树中查找值
 *
 * @param tree 树
 * @param value 查找值
 * @param column 查找字段
 */
export const treeFindById = (tree, value, column) => {
  let datac;

  for (let data of tree) {
    if (data[column] === value) {
      return data;
    }

    if (data.hasChildren && data.children) {
      datac = treeFindById(data.children, value, column);
      if (datac) {
        return datac;
      }
    }
  }

  return datac;
};

/**
 * 删除TREE中的一个对象
 * @returns {string}
 * @param tree
 * @param id
 */
export const delItemById = (tree, id) => {

  let row;

  for (let i = 0; i < tree.length; i++) {
    if (tree[i].id === id){
      row = {};
      row.data = tree[i];
      row.index = i;
      tree.splice(i,1);
      break;
    }

    if (tree[i].children){
      row = delItemById(tree[i].children,id);
      if (row){
        return row;
      }
    }
  }

  return row;
}

/**
 * 给TREE添加一个对象
 * @returns {string}
 * @param tree
 * @param row
 * @param index
 */
export const addItemById = (tree, row, index) => {

  if (row){

    if (row.parentId === '-1' || row.parentId === undefined){
      tree.splice(index,0,row);
    } else {

      for (let i = 0; i < tree.length; i++) {

        const data = tree[i];

        if (row.parentId === data.id){
          data.hasChildren = true;
          if (data.children === undefined){
            data.children = []
          }
          data.children.splice(index,0,row);
          break;
        }

        if (data.children){
          addItemById(data.children,row,index);
        }

      }
    }

  }

}

export const downloadFile = async (mark) => {
  await request.get(window.urllist.download+mark, {responseType: 'blob'}).then(resp => {
    if (resp.status === 200){
      download(resp);
    }else {
      this.$message.error(resp.data.message);
    }
  })
}

export const download = (resp, options = {}) => {
  let blob = new Blob([resp.data], {type: options.fileType ? options.fileType : 'application/octet-binary'})
  //创建下载的链接
  let href = window.URL.createObjectURL(blob)
  downloadBlob(href, options.fileName ? options.fileName : decodeURIComponent(resp.headers.filename))
}

let downloadBlob = (blobUrl, fileName, revokeObjectURL) => {
  let downloadElement = document.createElement('a')
  downloadElement.href = blobUrl
  //下载后文件名
  downloadElement.download = fileName
  document.body.appendChild(downloadElement)
  //点击下载
  downloadElement.click()
  //下载完成移除元素
  document.body.removeChild(downloadElement)
  if (revokeObjectURL == null || revokeObjectURL) {
    //释放掉blob对象
    window.URL.revokeObjectURL(blobUrl)
  }
}